package edu.ynu.hhy.architectureclass.config;

import edu.ynu.hhy.architectureclass.entity.User;
import edu.ynu.hhy.architectureclass.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principals.getPrimaryPrincipal();

        // 根据用户类型添加角色
        if (user.getType() == 1) {
            authorizationInfo.addRole("admin");
        } else {
            authorizationInfo.addRole("user");
        }

        // 添加权限
        authorizationInfo.addStringPermission("user:view");

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());

        User user = userService.findByUsername(username);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }

        // 对用户输入的密码进行MD5加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());

        // 比较加密后的密码
        if (!user.getPassword().equals(encryptedPassword)) {
            throw new IncorrectCredentialsException("密码错误");
        }

        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}